package com.example.zuul;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;

/**
 * @author 吕一明
 * @公众号 码客在线
 *
 * 限流
 */
//@Component
public class LimterFilter extends ZuulFilter {

    //guava的令牌桶算法
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

    @Override
    public String filterType() {
        return "pre";// pre,post,routing
    }

    @Override
    public int filterOrder() {
        return 0;// 越小越先
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        if(!RATE_LIMITER.tryAcquire()) {
            throw new RuntimeException("占坑失败~~");
        }

        System.out.println("-------->没限流");

        return null;
    }
}
